<template>
  <div>
    <div v-show="firstStep">
      <el-form :model="basicInfo" :rules="rules" ref="basicInfo" class="demo-ruleForm" label-width="180px">
        <div class="detail-info" style="margin-top: 50px">
          <div class="form-item">
            <h4>基本信息</h4>
              <el-form-item label="所属分公司" label-width="180px" required>
                <el-select v-if="!brachDisabled" v-model="basicInfo.branchId" :disabled="brachDisabled"
                @change="getDeptList" @visible-change="visibleChange" style="width:200px" placeholder="分公司">
                  <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
                </el-select>
                <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:200px"></el-input>
              </el-form-item>
              <el-form-item label="所属部门" label-width="180px" prop="departmentId" required>
                <el-select v-if="!brachDisabled" v-model="basicInfo.departmentId" :disabled="brachDisabled" placeholder="所属部门" style="width:195px">
                  <el-option v-for="(item, index) in this.deptList" :value="item.org_id" :label="item.org_name" :key="index"></el-option>
                </el-select>
                <el-input v-if="brachDisabled" v-model="this.showDept" disabled style="width:195px"></el-input>
              </el-form-item>
              <el-form-item label="客资类型" prop="customerType">
                <el-select v-model="basicInfo.customerType" style="width:220px" :loading="customerTypeLoading" placeholder="客资类型">
                  <!-- <el-option value="1" label="普通超市"></el-option> -->
                  <el-option v-for="(item, index) in customerTypeList"
                  :key="index"
                  :label="item.name"
                  :value="item.id.toString()"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="促销费用" prop="salesCosts">
                <!-- <el-input v-model="basicInfo.salesCosts" style="width:210px"></el-input> -->
                <el-select v-model="basicInfo.salesCosts" @change="handleChangeSalesCosts" placeholder="请选择促销费用" :loading="saleCostLoading"  style="width:220px">
                  <el-option v-for="(item, index) in salesCostsList" :key="index" :label="item.promotionName" :value="item.id.toString()" ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="this.selectSalesCosts.type === 2 || this.selectSalesCosts.type === ''"
              label="供应商占比" prop="providerRatio">
                <el-input v-model="basicInfo.providerRatio" style="width:200px"></el-input>
                <span>%</span>
              </el-form-item>
          </div>
        </div>
        <div class="detail-info" style="margin-top: 50px">
          <div class="form-item">
            <h4>批次信息</h4>
            <el-form-item label="批次名称" prop="batchName">
              <el-input v-model="basicInfo.batchName" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="活动起止时间" prop="startStopTime">
              <el-date-picker :editable="false" v-model="basicInfo.startStopTime"
              @change="daterangeFormat($event, '活动')" type="daterange" value-format="yyyy-MM-dd"
              style="width:220px" placeholder="活动起止时间"
              :picker-options="pickerExpirationDate"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="展示时间" prop="showTime">
              <el-date-picker :editable="false" v-model="basicInfo.showTime"
              :disabled="showTimeDisable"
              @change="daterangeFormat($event, '展示')" type="daterange" value-format="yyyy-MM-dd"
              style="width:220px" placeholder="展示时间"
              :picker-options="pickerOptionsShow"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="满返纬度" required>
              <el-radio-group v-model="basicInfo.latType" @change="radioChange">
                <el-radio label="1">订单</el-radio>
                <el-radio label="2">部分商品</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="满返规则" required>
              <el-radio-group v-model="basicInfo.fullRule">
                <el-radio v-if="basicInfo.latType === '1'" label="1">阶梯</el-radio>
                <el-radio label="2">每满</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="basicInfo.fullRule === '2'" required>
              <el-radio-group v-model="basicInfo.fullRuleRule">
                <el-radio label="1">金额</el-radio>
                <el-radio label="2">数量</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="basicInfo.fullRule === '2' && basicInfo.fullRuleRule === '1'"
            label="满返金额" prop="fullReturnMoney" required >
              <el-input v-model="basicInfo.fullReturnMoney" placeholder="满返金额" style="width:210px"></el-input>
            </el-form-item>
            <el-form-item v-if="basicInfo.fullRule === '2' && basicInfo.fullRuleRule === '2'"
            label="满返数量" prop="fullReturnMoney" required>
              <el-input v-model="basicInfo.fullReturnMoney" placeholder="满返数量" style="width:210px"></el-input>
            </el-form-item>
            <el-form-item v-if="basicInfo.fullRule === '2'" label="参与次数" required>
              <el-select v-model="basicInfo.joinType" placeholder="">
                <el-option value="1" label="不限"></el-option>
                <el-option value="2" label="全程"></el-option>
                <el-option value="3" label="每单"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicInfo.fullRule === '2' && (basicInfo.joinType === '3' || basicInfo.joinType === '2')"
            label="反" prop="returnTimes">
              <el-input v-model="basicInfo.returnTimes" style="width:100px"></el-input> 次
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div style="margin: 20px auto 80px; width: 17%">
        <el-button @click="nextStep('basicInfo')" type="success">下一步</el-button>
        <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
      </div>
    </div>
    <div v-show="secondStep">
      <div v-if="isCoupon" class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>优惠券信息</h4>
          <el-button type="primary" :disabled="choseCodeDisabled" @click="handleChooseCode">选择优惠券</el-button>
          <el-table v-if="isCoupon" :data="redeemCodeDetails" border style="margin-top:20px;width: 100%">
            <el-table-column v-if="this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1'" label="满足金额" width="80" align="center">
              <template scope="scope">
                <el-input v-model="scope.row.fullMoney"
                @blur="valueToTable(scope.row, 'fullMoney', $event, scope.$index)"
                placeholder="满足金额"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="优惠券ID" prop="ticketId" align="center" width="80"></el-table-column>
            <el-table-column label="优惠券名称" prop="ticketName" align="center" width="100"></el-table-column>
            <el-table-column label="类型" align="center" width="100">
              <template scope="scope">
                <span v-if="scope.row.ticketType === '1'">现金券</span>
                <span v-if="scope.row.ticketType === '2'">满减券</span>
                <span v-if="scope.row.ticketType === '3'">实物券</span>
                <span v-if="scope.row.ticketType === '4'">品牌现金券</span>
                <span v-if="scope.row.ticketType === '6'">品类券</span>
              </template>
            </el-table-column>
            <el-table-column label="面值" prop="ticketMoney" align="center" width="60"></el-table-column>
            <el-table-column label="满多少元可用" prop="fullUse" align="center" width="100"></el-table-column>
            <el-table-column label="满多少件可用" prop="numLimit" align="center" width="100"></el-table-column>
            <el-table-column label="有效期类型" align="center" width="120">
              <template scope="scope">
                <el-select v-model="scope.row.expiryDateType" placeholder="有效期类型" @change="changeExpirationType($event, scope.row)">
                  <el-option value="1" label="时间段"></el-option>
                  <el-option value="2" label="截止时间"></el-option>
                  <el-option v-if="selectSalesCosts.type === 1" value="3" label="天数"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="有效期" align="center" min-width="225">
              <template scope="scope">
                <el-date-picker :editable="false" :clearable="false"
                v-if="scope.row.expiryDateType==='1'" v-model="scope.row.startTime"
                @change="valueToTable(scope.row, 'startTime', $event, scope.$index)"
                style="width:47%" placeholder="开始时间"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                ></el-date-picker>
                <el-date-picker :editable="false" :clearable="false"
                v-if="scope.row.expiryDateType==='1' || scope.row.expiryDateType==='2'"
                v-model="scope.row.endTime"
                @change="valueToTable(scope.row, 'endTime', $event, scope.$index)"
                style="width:47%" placeholder="结束时间"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                ></el-date-picker>
                <el-input v-if="scope.row.expiryDateType === '3'"
                v-model="scope.row.days" @blur="valueToTable(scope.row, 'days', $event, scope.$index)"
                style="width:45%" placeholder="请输入天数"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="每人/数量" align="center" width="85">
              <template scope="scope">
                <el-input v-model="scope.row.ticketTimes" @blur="valueToTable(scope.row, 'ticketTimes', $event, scope.$index)" placeholder="每人/数量"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="建券人" prop="ticketUser" align="center" width="65"></el-table-column>
            <el-table-column label="操作" align="center" width="50">
              <template scope="scope">
                <el-button type="text" size="small" @click="deleteCoupon('优惠券', redeemCodeDetails, chooseCouponTableList, scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog title="选择优惠券" :visible.sync="couponDialog">
            <el-row style="margin-top:20px">
              <el-form :model="chooseCouponInfo">
                <el-col :span="6" style="margin-right:10px">
                  <el-form-item label="券类型">
                    <el-select v-model="chooseCouponInfo.ticketType" placeholder="请选择券类型" style="width:130px">
                      <el-option v-for="(item, index) in ticketTypeGroup"
                      :key="index"
                      :value="item.ticketType.toString()"
                      :label="item.tname"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7" style="margin-right:10px">
                  <el-form-item label="优惠券名称">
                    <el-input v-model="chooseCouponInfo.tname" placeholder="优惠券名称" style="width:130px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="7" style="margin-right:10px">
                  <el-form-item label="优惠券ID">
                    <el-input v-model="chooseCouponInfo.id" placeholder="优惠券ID" style="width:130px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3" >
                  <el-button type="primary" style="float:right" @click="searchCouponGoods('优惠券')">搜索</el-button>
                </el-col>
                <el-table :data="chooseCouponTableList" border v-loading="searchLoading">
                  <el-table-column prop="ticketId" label="优惠券ID" align="center"></el-table-column>
                  <el-table-column prop="ticketName" label="优惠券名称" align="center"></el-table-column>
                  <el-table-column label="类型" align="center">
                    <template scope="scope">
                      <span v-if="scope.row.ticketType === '1'">现金券</span>
                      <span v-if="scope.row.ticketType === '2'">满减券</span>
                      <span v-if="scope.row.ticketType === '3'">实物券</span>
                      <span v-if="scope.row.ticketType === '4'">品牌现金券</span>
                      <span v-if="scope.row.ticketType === '6'">品类券</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ticketMoney" label="面值" align="center"></el-table-column>
                  <el-table-column prop="fullUse" label="满多少元可用" align="center"></el-table-column>
                  <el-table-column prop="numLimit" label="满多少件可用" align="center" width="100"></el-table-column>
                  <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                  <el-table-column label="操作" align="center">
                    <template scope="scope">
                      <!--<el-button v-if="scope.row.operation === 0" @click="addCode(scope.row, chooseCouponTableList[scope.$index], '优惠券')" type="text">添加</el-button>-->
                      <el-button @click="addCode(scope.row, chooseCouponTableList[scope.$index], '优惠券')" type="text">添加</el-button>
                      <el-button v-if="scope.row.operation === 1" @click="recallCode(scope.row, redeemCodeDetails, '优惠券')" type="text">撤回</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @current-change="handleCurrentChange($event, '优惠券')"
                  :page-size="Number(chooseCouponInfo.pageSize)"
                  layout="total, prev, pager, next"
                  :total="Number(chooseCouponInfo.total)"
                  style="padding-top:10px;text-align: right;">
                </el-pagination>
              </el-form>
            </el-row>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="couponDialog = false">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
      <div v-if="isGoods" class="detail-info" v-loading="uploadLoading" element-loading-text="正在导入，请稍后......">
        <div class="form-item" style="margin-bottom:0">
          <h4>商品信息</h4>
          <el-col :span="2">
            <el-button type="primary" @click="handleChooseGoods('', '1')">选择商品</el-button>
          </el-col>
          <el-col :span="6">
            <el-upload
              class="upload-demo"
              :action="url"
              :on-success="uploadSuccess"
              :before-upload="uploadBefore"
              :on-remove="removeFlie"
              :file-list="fileList"
              accept=".xlsx,.xls"
              :data="uploadData"
              >
              <el-button :disabled="primaryDisabled" type="primary">导入商品</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且只能上传一个文件</div>
            </el-upload>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" style="margin-left:-185px">
              <a style="text-decoration:none; color:#fff" href="/static/template/满返模板.xlsx">下载模板</a>
            </el-button>
          </el-col>
          <el-table v-if="isCoupon" :data="goodsDetails" border style="margin-top:20px;width: 100%">
            <el-table-column prop="productId" label="商品ID" align="center"></el-table-column>
            <el-table-column prop="productName" label="商品名称" align="center"></el-table-column>
            <el-table-column prop="units" label="单位" align="center"></el-table-column>
            <el-table-column prop="productSize" label="规格" align="center"></el-table-column>
            <el-table-column prop="price" label="系统售价" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template scope="scope">
                <el-button type="text" @click="deleteCoupon('商品', goodsDetails, goodsTableList, scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="inActivity">
            <h5>参加活动商品</h5>
            <el-table :data="inActivityDetails" border style="margin-top:20px;width: 100%">
              <el-table-column prop="productId" label="商品ID" align="center"></el-table-column>
              <el-table-column prop="productName" label="商品名称" align="center"></el-table-column>
              <el-table-column prop="units" label="单位" align="center"></el-table-column>
              <el-table-column prop="productSize" label="规格" align="center"></el-table-column>
              <el-table-column prop="price" label="售价系统" align="center"></el-table-column>
              <!-- <el-table-column label="操作" align="center">
                <template scope="scope">
                  <el-button type="text" @click="deleteCoupon(goodsDetails, scope.$index)">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <el-dialog title="选择商品" size="large" :visible.sync="goodsDialog" custom-class="goodsDialog">
            <el-form>
              <el-row style="margin-top:20px">
                <el-col :span="9">
                  <el-form-item label="分类">
                    <el-select clearable v-model="chooseGoodsInfo.firstCate" @change="handleChooseGoods($event, '2')" style="width:110px" placeholder="一级分类">
                      <el-option v-for="(item, index) in firstClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                    </el-select>
                    <el-select clearable v-model="chooseGoodsInfo.secondCate" @change="handleChooseGoods($event, '3')" style="width:110px" placeholder="二级分类">
                      <el-option v-for="(item, index) in secondClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                    </el-select>
                    <el-select clearable v-model="chooseGoodsInfo.thirdCate" style="width:110px" placeholder="三级分类">
                      <el-option v-for="(item, index) in threeClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="品牌">
                    <el-select clearable v-model="chooseGoodsInfo.fourCate" style="width:120px" placeholder="品牌">
                      <el-option v-for="(item, index) in brandGroup" :label="item.brandName" :value="item.brandId" :key="index"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="商品ID">
                    <el-input v-model="chooseGoodsInfo.hmpId" style="width:120px" placeholder="商品ID"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="商品名称">
                    <el-input v-model="chooseGoodsInfo.hmpName" style="width:120px" placeholder="商品名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button type="primary" @click="searchCouponGoods('商品', '搜索')">搜索</el-button>
                </el-col>
              </el-row>
              <el-table ref="table" :data="goodsTableList" border @selection-change="selectChange" v-loading="searchLoading">
                <el-table-column type="selection" :selectable="checkSelectAble" :reserve-selection="false" align="center" label="全选"></el-table-column>
                <el-table-column prop="productId" align="center" label="商品ID"></el-table-column>
                <el-table-column prop="productName" align="center" label="商品名称"></el-table-column>
                <el-table-column prop="units" align="center" label="单位"></el-table-column>
                <el-table-column prop="productSize" align="center" label="规格"></el-table-column>
                <el-table-column prop="price" align="center" label="系统售价"></el-table-column>
                <el-table-column prop="isActivity" align="center" label="当前活动"></el-table-column>
                <el-table-column align="center" label="操作">
                  <template scope="scope">
                    <el-button v-if="scope.row.operation === 0 && scope.row.isActivity ===''" @click="addCode(scope.row, goodsTableList[scope.$index], '商品')" type="text">添加</el-button>
                    <el-button v-if="scope.row.operation === 1 && scope.row.isActivity ===''" @click="recallCode(scope.row, goodsDetails, '商品')"  type="text">撤销</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row>
                <el-col :span="12">
                  <el-button type="primary" @click="batchAdd" style="margin-top:20px">批量添加</el-button>
                </el-col>
                <el-col :span="12">
                  <el-pagination
                    @current-change="handleCurrentChange($event, '商品')"
                    :page-size="Number(chooseGoodsInfo.pageSize)"
                    layout="total, prev, pager, next"
                    :total="Number(chooseGoodsInfo.total)"
                    style="padding-top:10px;text-align: right;">
                  </el-pagination>
                </el-col>
              </el-row>
            </el-form>
          </el-dialog>
        </div>
      </div>
      <div class="detail-info">
        <div class="form-item" style="margin-bottom:0">
          <h4>备注</h4>
          <el-input style="width:400px" type="textarea" placeholder="请输入备注" v-model="basicInfo.remark"></el-input>
        </div>
      </div>
      <div style="margin: 20px auto 20px; width: 20%">
        <el-button @click="onSubmitValid(2, 'basicInfo')" type="success">提交</el-button>
        <el-button @click="onSubmitValid(1, 'basicInfo')" type="warning">暂存</el-button>
        <el-button @click="goBack" type="danger">返回</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../config/settings.js'
  import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  import moment from 'moment'
  // import Vue from 'vue'
  export default {
    mixins: [mixins],
    data () {
      var self = this
      var checkGysproportion = (rule, value, callback) => { // 验证供应商占比
        var text = rule.field === 'providerRatio' ? '供应商占比' : '满返金额/数量'
        if (!value) {
          return callback(new Error(text + '不能为空'))
        } else {
          var reg = /^[0-9]\d*$/
          if (reg.test(value)) {
            value = value.toString()
            if (value.indexOf(0) === 0 && value.length > 1) {
              callback(new Error('不能以0开头'))
            }
            callback()
          } else {
            callback(new Error('供应商占比必须正整数'))
          }
        }
      }
//      var nameTest = (rule, value, callback) => { // 批次名称验证
//        if (!value) {
//          return callback(new Error('请输入批次名称'))
//        } else {
//          if (value.length > 16) {
//            callback(new Error('您输入的名称过长!'))
//          } else {
//            callback()
//          }
//        }
//      }
      var checkReturnTimes = (rule, value, callback) => { // 验证反多少次
        if (!value) {
          return callback(new Error('返多少次不能为空'))
        } else {
          var re = /^[1-9]\d*$/
          if (!re.test(value)) {
            callback(new Error('请输入正整数'))
          } else {
            callback()
          }
        }
      }
      return {
        pickerExpirationDate: { // 截止日期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptions: { // 禁用时间段
          disabledDate (time) {
            return time.getTime() < new Date(self.selectSalesCosts.stime).getTime() || time.getTime() > new Date(self.selectSalesCosts.etime).getTime()
          }
        },
        pickerOptionsShow: {
          disabledDate (time) {
            // console.log(self.basicInfo.startTime)
            // console.log(self.getDateStr(0, self.basicInfo.startTime))
            return time.getTime() < new Date(self.getDateStr(-1, self.basicInfo.startTime)).getTime()
          }
        },
        basicInfo: {
          branchId: '',
          departmentId: '',
          salesCosts: '', // 促销费用
          providerRatio: '', // 供应商补差占比
          customerType: '1', // 客资类型
          remark: '', // 备注
          batchName: '', // 批次名称
          startStopTime: [], // 活动起止时间
          startTime: '',
          endTime: '',
          showTime: [], // 展示时间
          showStartTime: '',
          showEndTime: '',
          latType: '1', // 满返纬度
          fullRule: '1', // 满返规则
          fullRuleRule: '1', // 满返规则
          fullReturnMoney: '', // 满返金额
          joinType: '1', // 参与次数
          returnTimes: '' // 反多少次
        },
        showTimeDisable: true, // 展示时间禁用
        // pageLoading: false,
        showBranchName: '', // 页面展示的公司名称
        showDeptName: '', // 页面展示的部门名称
        customerTypeList: [], // 客资类型数组
        customerTypeLoading: true, // 客资类型loading
        salesCostsList: [], // 促销费用数组
        saleCostLoading: true, // 促销费用loading
        selectSalesCosts: {}, // 选中的促销费用
        firstStep: true, // 默认显示 第一步
        secondStep: false, // 下一步
        isCoupon: false, // 是否显示优惠券
        isGoods: false, // 是否显示商品
        isCoupon2: false, // 是否显示优惠券二
        fileId: '', // 上传回来的id
        fileList: [],
        url: '',  // 上传路径
        uploadLoading: false, // 上传加载
        searchLoading: false, // 商品优惠券加载
        choseCodeDisabled: false, // 选择优惠券按钮
        primaryDisabled: false, // 上传按钮
        redeemCodeDetails: [], // 优惠券数组
        goodsDetails: [], // 商品数组
        inActivity: false,
        inActivityDetails: [], // 在活动中的商品
        validityType: '2', // 有效期类型
        validity: '', // 有效期
        creatTotal: '', // 生成总数
        tableTime: '',
        tableTimeRange: '',
        remark: '', // 备注
        chooseCouponTableList: [], // 优惠券弹框table list
        couponValid: false, // 验证优惠券
        goodsValid: false, // 商品验证
        couponDialog: false, // 优惠券弹框
        chooseCouponInfo: { // 选择优惠券条件
          id: '', // 优惠券id
          ticketType: '1', // 优惠券类型
          tname: '', // 优惠券名称
          page: '1',
          pageSize: '20',
          total: 0
        },
        ticketTypeGroup: [], // 券类型数组
        goodsTableList: [],
        chooseGoodsInfo: { // 选择商品条件
          firstCate: '',
          secondCate: '',
          thirdCate: '',
          fourCate: '',
          hmpId: '',
          hmpName: '',
          page: '1',
          pageSize: '20',
          total: 0
        },
        uploadData: {
          branchId: ''
        },
        firstClassifyGroup: [], // 一级分类数组
        secondClassifyGroup: [], // 二级分类数组
        threeClassifyGroup: [], // 三级分类数组
        brandGroup: [], // 品牌数组
        goodsDialog: false, // 商品弹框
        selectGroup: [],
        sendDetailPageSize: 10,
        sendDetailPage: 1,
        sendDetailDialog: false, // 发送明细
        sendDetail: [], // 发放明细
        sendDetailCheck: [], // 查看发放明细
        sendDetailType: 1,
        isCreateOrUpdate: '',
        text: '',
        menuId: '',
        // subDisabled: false,
        rules: {
          departmentId: [ // 促销费用
            {required: true, type: 'number', message: '请选择所属部门', trigger: 'change'}
          ],
          salesCosts: [ // 促销费用
            {required: true, message: '请选择促销费用', trigger: 'change'}
          ],
          customerType: [ // 客资类型
            {required: true, message: '请选择客资类型', trigger: 'change'}
          ],
          providerRatio: [ // 供应商占比
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          fullReturnMoney: [ // 满返金额
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          returnTimes: [ // 满返金额
            {validator: checkReturnTimes, trigger: 'blur'}
          ],
          batchName: [ // 批次名称
            {required: true, message: '请输入批次名称', trigger: 'blur'},
            { min: 0, max: 16, message: '长度不能超过16个字符', trigger: 'blur' }
          ],
          startStopTime: [ // 发放时间
            {type: 'array', required: true, message: '请选择活动起止日期', trigger: 'change'}
          ],
          showTime: [ // 发放时间
            {type: 'array', required: true, message: '请选择展示日期', trigger: 'change'}
          ]
        },
        showBranch: '',
        showDept: '',
        newBranchId: '',
        createBranchId: '',
        brachDisabled: false,
        deptList: [],
        visible: false
      }
    },
    methods: {
      getDeptList (val) { // 获取部门
        console.log(this.visible)
        this.uploadData.branchId = val
        this.searchSalesCosts()
        if (this.visible === true) {
          console.log('aaa')
          this.basicInfo.departmentId = ''
          this.basicInfo.salesCosts = ''
        }
        var _data = {}
        var self = this
        setTimeout(() => {
          console.log(self.branchList)
          self.branchList.forEach(element => {
            if (val === element.branch_Id) {
              console.log(val === element.branch_Id)
              _data.orgId = element.org_id
              self.newBranchId = element.org_id
            }
          })
          console.log(_data)
          if (JSON.stringify(_data) === '{}') {
            return
          } else {
            getInfo.department(_data, (res) => {
              console.log(res)
              if (res.message === 'ok') {
                if (val === 1) {
                  self.deptList = []
                  res.content.forEach(element => {
                    if (element.org_name.indexOf('公司') === -1) {
                      self.deptList.push(element)
                    }
                  })
                  self.matchDept()
                } else {
                  self.deptList = res.content
                  self.matchDept()
                }
              } else {
                self.message(res.message, 'error')
              }
            })
          }
        }, 500)
      },
      matchDept () { // 匹配 当前登录人的部门与部门列表
        console.log(this.deptList)
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          console.log(Number(this.basicInfo.departmentId) === Number(element.org_id))
          console.log(Number(this.basicInfo.departmentId), Number(element.org_id))
          if (Number(this.basicInfo.departmentId) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.basicInfo.departmentId = ''
            }
          }
        }
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      radioChange (val) { // 满返纬度赋值
        this.basicInfo.fullRule = val === '1' ? '1' : '2'
      },
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchSalesCosts (row) { // 查询促销费用
        var _data = {
          branchId: this.basicInfo.branchId,
          activityType: '-1'
        }
        activity.cxfy.allList(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.salesCostsList = res.content
            this.saleCostLoading = false
            // this.pageLoading = false
            // if (row) {
            //   this.searchDetail(this.$store.state.tab.uid)
            // }
          }
        })
      },
      handleChangeSalesCosts (val) { // 选择促销费用
        for (var index = 0; index < this.salesCostsList.length; index++) {
          var element = this.salesCostsList[index]
          if (element.id === Number(val)) {
            if (element.promotionType === 1) {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: '',
                etime: ''
              }
            } else {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: this.timeDeltSecond(element.promotionBeginTime),
                etime: this.timeDeltSecond(element.promotionEndTime)
              }
            }
          }
        }
      },
      uploadSuccess (response, file, fileList) { // 上传成功
        console.log(arguments)
        if (response.message === 'ok') {
          this.uploadLoading = false
          this.message('上传成功', 'success')
          this.goodsDetails = response.content.notInActivity
          this.goodsDetails.forEach(element => {
            element.productId = element.hmpId
            element.productName = element.hmpName
            element.units = element.hmpUnit
            element.productSize = element.hmpNorms
            element.price = element.hmpBuyPrice
          })
          console.log(this.goodsDetails)
          if (response.content.inActivity.length !== 0) {
            this.inActivity = true
            this.inActivityDetails = response.content.inActivity
            this.inActivityDetails.forEach(element => {
              element.productId = element.hmpId
              element.productName = element.hmpName
              element.units = element.hmpUnit
              element.productSize = element.hmpNorms
              element.price = element.hmpBuyPrice
            })
          }
          this.primaryDisabled = true
          this.basicInfo.fileName = file.name
          // this.goodsValid = true
          this.matchOperation('商品', this.goodsTableList, this.goodsDetails)
        } else {
          this.uploadLoading = false
          this.resetPrimary()
          this.message('上传失败', 'error')
          // this.goodsValid = false
        }
      },
      uploadBefore (file) { // 上传之前
        console.log(file)
        this.uploadLoading = true
      },
      removeFlie (file, fileList) { // 上传文件删除
        if (fileList.length === 0) {
          // this.primaryDisabled = false
          this.resetPrimary()
          this.goodsDetails = []
          this.inActivity = false
          this.inActivityDetails = []
          // this.basicInfo.fileName = ''
          // this.basicInfo.id = ''
        }
      },
      searchCouponGoods (type, text) { // 查询优惠券/商品
        // console.log('查询优惠券')
        this.searchLoading = true
        if (type === '商品') {
          var _data = this.chooseGoodsInfo
          _data.branchId = this.basicInfo.branchId
          _data.showType = [1, 3, 4]
          // delete _data.total
          this.chooseGoodsInfo.page = text ? 1 : this.chooseGoodsInfo.page
          console.log(_data)
          getInfo.searchProduct(_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.searchLoading = false
              if (res.content.content !== null) {
                // this.goodsTableList = []
                // for (var index = 0; index < res.content.content.length; index++) {
                //   // var eleGoods = this.goodsTableList[index]
                //   var eleRes = res.content.content[index]
                res.content.content.forEach((eleRes, index) => {
                  eleRes.productId = eleRes.hmpId // 商品id
                  eleRes.productName = eleRes.hmpName // 商品名称
                  eleRes.units = eleRes.hmpUnit // 单位
                  eleRes.productSize = eleRes.hmpNorms // 规格
                  eleRes.price = eleRes.hmpBuyPrice // 系统售价
                  eleRes.operation = 0 // 操作
                  // 'newActivity': '满减' // 当前活动
                  eleRes.isActivity = eleRes.isActivity === null ? '' : eleRes.isActivity.join(',') // 当前活动 eleRes.isActivity
                })
                this.goodsTableList = res.content.content
                  // this.goodsTableList.push({
                  //   'productId': eleRes.hmpId, // 商品id
                  //   'productName': eleRes.hmpName, // 商品名称
                  //   'units': eleRes.hmpUnit, // 单位
                  //   'productSize': eleRes.hmpNorms, // 规格
                  //   'price': eleRes.hmpBuyPrice, // 系统售价
                  //   'operation': 0, // 操作
                  //   // 'newActivity': '满减' // 当前活动
                  //   'isActivity': eleRes.isActivity === null ? '' : eleRes.isActivity.join(',') // 当前活动 eleRes.isActivity
                  // })
                // }
                console.log(this.goodsTableList)
                this.chooseGoodsInfo.total = res.content.count
                this.chooseGoodsInfo.page = res.content.page
                this.matchOperation(type, this.goodsTableList, this.goodsDetails)
              } else {
                this.goodsTableList = []
              }
            } else {
              this.searchLoading = false
            }
          })
        } else if (type === '优惠券') {
          var _dataCode = this.chooseCouponInfo
          _dataCode.branchId = this.basicInfo.branchId
          _dataCode.departmentId = this.basicInfo.departmentId
          _dataCode.bid = this.newBranchId
          // delete _dataCode.total
          console.log(_dataCode)
          getInfo.couponList(_dataCode, (res) => {
            if (res.message === 'ok') {
              console.log(res)
              this.searchLoading = false
              if (res.content.content !== null) {
                this.chooseCouponTableList = []
                for (var k = 0; k < res.content.content.length; k++) {
                  var eleCode = res.content.content[k]
                  this.chooseCouponTableList.push({
                    'ticketId': eleCode.id,
                    'ticketName': eleCode.tname,
                    'ticketType': this.chooseCouponInfo.ticketType,
                    'ticketMoney': eleCode.tcost !== null ? eleCode.tcost : '',
                    'numLimit': eleCode.numLimit !== null ? eleCode.numLimit : '', // 满多少件可用
                    'fullUse': eleCode.fulluse !== null ? eleCode.fulluse : '',
                    'remark': eleCode.remark,
                    'operation': 0,
                    'phpTicketId': eleCode.phpId
                  })
                }
                this.chooseCouponInfo.total = res.content.count
                this.chooseCouponInfo.page = res.content.page
                this.matchOperation(type, this.chooseCouponTableList, this.redeemCodeDetails)
              } else {
                this.chooseCouponTableList = []
              }
            }
          })
        }
      },
      handleChooseCode () { // 选择优惠券按钮
        this.couponDialog = true
        this.searchCodeType()
      },
      searchCodeType () { // 查询券类型
        var _data = ''
        getInfo.couponType(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.ticketTypeGroup = res.content
          }
        })
      },
      handleChooseGoods (id, group) { // 选择商品按钮
        switch (group) {
          case '1':
            this.goodsDialog = true
            this.searchGoods(id, group)
            break
          case '2':
            if (id === '') {
              this.secondClassifyGroup = []
              this.threeClassifyGroup = []
              this.brandGroup = []
              this.chooseGoodsInfo.secondCate = ''
              this.chooseGoodsInfo.thirdCate = ''
              this.chooseGoodsInfo.fourCate = ''
            } else {
              this.searchGoods(id, group)
            }
            break
          default:
            if (id === '') {
              this.threeClassifyGroup = []
              this.brandGroup = []
              this.chooseGoodsInfo.thirdCate = ''
              this.chooseGoodsInfo.fourCate = ''
            } else {
              this.searchGoods(id, group)
            }
            break
        }
      },
      matchOperation (text, arr1, arr2) { // 查询时 匹配优惠券数组 和 已选则优惠券数组 显示 添加或撤回
        console.log(arguments)
        console.log(arr1)
        console.log(arr2)
        if (arr1.length !== 0) {
          arr1.forEach((allEle, i) => {
            if (arr2.length === 0) {
              allEle.operation = 0
            } else {
              arr2.forEach((selectEle, k) => {
                if (text === '优惠券') {
                  if (Number(allEle.ticketId) === Number(selectEle.ticketId) && Number(allEle.ticketType) === Number(selectEle.ticketType)) {
                    // console.log('aaaa')
                    allEle.operation = 1
                  }
                } else {
                  if (Number(allEle.productId) === Number(selectEle.productId)) {
                    // console.log(Number(allEle.productId) === Number(selectEle.productId))
                    // console.log(Number(allEle.productId))
                    // console.log(Number(selectEle.productId))
                    // console.log(i)
                    allEle.operation = 1
                    // console.log(allEle)
                    // console.log(allEle.operation)
                  } else {
                    if (i === arr1.length - 1) {
                      console.log('aaa')
                      allEle.operation = 0
                    }
                  }
                }
              })
            }
          })
        }
        // for (let i = 0; i < arr1.length; i++) {
        //   var allEle = arr1[i]
        //   if (arr2.length === 0) {
        //     arr1[i].operation = 0
        //   } else {
        //     this.arr2.forEach((element, k) => {
        //       if (text === '优惠券') {
        //         if (Number(allEle.ticketId) === Number(selectEle.ticketId) && Number(allEle.ticketType) === Number(selectEle.ticketType)) {
        //           // console.log('aaaa')
        //           allEle.operation = 1
        //         }
        //       } else {
        //         if (Number(allEle.productId) === Number(selectEle.productId)) {
        //           allEle.operation = 1
        //         } else {
        //           allEle.operation = 0
        //         }
        //       }
        //     })
            // for (let k = 0; k < arr2.length; k++) {
            //   var selectEle = arr2[k]
            //   if (text === '优惠券') {
            //     if (Number(allEle.ticketId) === Number(selectEle.ticketId) && Number(allEle.ticketType) === Number(selectEle.ticketType)) {
            //       // console.log('aaaa')
            //       arr1[i].operation = 1
            //     }
            //   } else if (text === '商品') {
            //     if (Number(allEle.productId) === Number(selectEle.productId)) {
            //       console.log(Number(allEle.productId) === Number(selectEle.productId))
            //       console.log(Number(allEle.productId))
            //       console.log(Number(selectEle.productId))
            //       console.log(i)
            //       // arr1[i].operation = 1
            //       // Vue.set(this.goodsTableList[i].operation, i, 1)
            //       console.log(this.goodsTableList[i].operation)
            //       arr1[i].operation = 1
            //       console.log(this.goodsTableList[i].operation)
            //       console.log(this.goodsTableList[i])
            //     } else {
            //       arr1[i].operation = 0
            //     }
            //   }
            // }
          // }
        // }
        console.log(this.goodsTableList)
      },
      searchGoods (id, group) { // 查询商品分类方法
        console.log('aaaa')
        getInfo.getCate({pid: id}, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            // console.log(res.content)
            if (group === '1') {
              this.firstClassifyGroup = res.content
            } else if (group === '2') {
              this.secondClassifyGroup = res.content
            } else if (group === '3') {
              this.searchBrand(id)
              this.threeClassifyGroup = res.content
            }
          }
        })
      },
      searchBrand (id) { // 查询品牌
        console.log(id)
        getInfo.getBrand({cateId: id}, (res) => {
          if (res.message === 'ok') {
            console.log(res)
            this.brandGroup = res.content
          }
        })
      },
      addCode (row, data, text) { // 添加优惠券或商品
        if (text === '优惠券') {
          if (this.basicInfo.fullRule === '2' && this.redeemCodeDetails.length >= 1) {
            this.message('添加失败！只能添加一条优惠券信息', 'error')
            data.operation = 0
          } else {
            var newRow = {
              ticketTimes: '', // 每人/数量
              startTime: '', // 开始时间
              ticketUser: this.userName, // 建券人
              days: '', // 天数
              endTime: '', // 结束时间
              expiryDateType: '1', // 有效期类型
              ticketId: row.ticketId, // 优惠券id
              ticketType: row.ticketType, // 优惠券类型
              fullUse: row.fullUse, // 满多少可用
              numLimit: row.numLimit,
              ticketName: row.ticketName, // 优惠券名称
              ticketMoney: row.ticketMoney, // 面值
              validity: '',
              fullMoney: '', // 满足金额
              phpTicketId: row.phpTicketId,
              valida: false // 验证
            }
            this.redeemCodeDetails.push(newRow)
            data.operation = 1
          }
        } else {
          this.goodsDetails.push(row)
          data.operation = 1
        }
        this.resetChoseCode()
      },
      batchAdd () { // 商品批量添加
        this.goodsDetails = this.goodsDetails.concat(this.selectGroup)
        this.matchOperation('商品', this.goodsTableList, this.goodsDetails)
        this.$refs.table.clearSelection(this.selectGroup)
      },
      checkSelectAble (row, index) { // 添加后清空选择状态
        return (row.operation !== 1 && row.isActivity === '')
      },
      recallCode (row, arr, text) { // 撤回
        console.log(arguments)
        for (var i = 0; i < arr.length; i++) {
          var element = arr[i]
          if (text === '优惠券') {
            if (Number(element.ticketId) === Number(row.ticketId) && Number(element.ticketType) === Number(row.ticketType)) {
              arr.splice(i, 1)
            }
          } else if (text === '商品') {
            if (Number(element.productId) === Number(row.productId)) {
              arr.splice(i, 1)
              if (arr.length === 0) {
                this.resetPrimary()
              }
            }
          }
        }
        row.operation = 0
        this.resetChoseCode()
      },
      resetChoseCode () { // 重置选择优惠券
        if (this.basicInfo.fullRule === '2' && this.redeemCodeDetails.length === 0) {
          this.choseCodeDisabled = false
        } else if (this.basicInfo.fullRule === '2' && this.redeemCodeDetails.length === 1) {
          this.choseCodeDisabled = true
        }
      },
      resetPrimary () { // 重置上传按钮状态
        this.primaryDisabled = false
        this.fileList = []
      },
      selectChange (selection) { // table多选框
        this.selectGroup = selection
        console.log(this.selectGroup)
      },
      handleCurrentChange (val, type) { // 分页
        if (type === '优惠券') {
          this.chooseCouponInfo.page = val
        } else if (type === '商品') {
          this.chooseGoodsInfo.page = val
        }
        this.searchCouponGoods(type)
      },
      changeExpirationType (val, row) {
        // row.startTime = ''
        // row.endTime = ''
        // row.days = ''
      },
      valueToTable (row, name, val, index) { // 有效期类型赋值
        if (val && val !== '') {
          if (row.expiryDateType === '1') {
            row[name] = val
            if (row.startTime !== '' && row.endTime !== '') {
              if (new Date(row.startTime) <= new Date(row.endTime)) {
              } else {
                console.log(row)
                this.message('结束时间不能小于开始时间', 'error')
                row[name] = ''
              }
            }
          } else if (row.expiryDateType === '2') {
            row[name] = val
          } else if (row.expiryDateType === '3') {
            row[name] = val
          }
          if (name === 'days' || name === 'ticketTimes' || name === 'fullMoney') {
            val = val.srcElement.value
            console.log(name)
            console.log(val)
            var text = ''
            if (name === 'days') { text = '天数' }
            if (name === 'ticketTimes') { text = '每人/张数' }
            if (name === 'fullMoney') { text = '满足金额' }
            var re = /^[1-9]\d*$/
            if (re.test(val)) {
              row[name] = val
            } else {
              this.message('第' + (index + 1) + '行' + text + '格式错误，请输入正整数！', 'error')
              row[name] = ''
            }
          }
        }
      },
      deleteCoupon (text, arr, arr2, index, row) { // 删除优惠券
        this.$confirm('您确定要删除该条' + text + '信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          arr.splice(index, 1)
          this.message('删除成功', 'success')
          if (text === '优惠券') {
            for (var i = 0; i < arr2.length; i++) {
              var element1 = arr2[i]
              if (Number(element1.ticketId) === Number(row.ticketId) && Number(element1.ticketType) === Number(row.ticketType)) {
                element1.operation = 0
              }
            }
          } else if (text === '商品') {
            for (var k = 0; k < arr2.length; k++) {
              var element2 = arr2[k]
              if (Number(element2.productId) === Number(row.productId)) {
                element2.operation = 0
              }
            }
          }
          if (arr.length === 0) {
            this.resetPrimary()
            this.inActivity = false
            this.inActivityDetails = []
          }
          this.resetChoseCode()
        }).catch(() => {
        })
      },
      searchDetail (row) { // 查询详情
        activity.yhqhd.mfgl.detail({id: row.id}, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            console.log(res.content)
            // this.pageLoading = false
            this.creatRedeemCodeDetail(res.content)
            this.basicInfo.branchId = res.content.branchId // 创建时公司是返回的公司id
            this.showBranch = res.content.branchName // 创建时公司是返回的公司名称
            this.basicInfo.departmentId = res.content.departmentId // 创建时公司是返回的部门id
            this.showDept = res.content.departName // 创建时公司是返回的部门名称
            this.createBranchId = this.branchOrgId // 创建时创建人新公司ID
            this.searchSalesCosts()
            this.$store.dispatch('pageLoading', false)
          } else {
            this.$store.dispatch('pageLoading', false)
            this.message('查看详情失败', 'error')
          }
        })
      },
      creatRedeemCodeDetail (res) { // 详情回填
        this.basicInfo.salesCosts = res.salesCosts.toString() // 促销费用
        this.basicInfo.providerRatio = res.providerRatio // 供应商补差占比
        this.basicInfo.customerType = res.customerType.toString() // 客资类型
        this.basicInfo.remark = res.remark // 备注
        this.basicInfo.batchName = res.batchName // 批次名称
        this.basicInfo.startStopTime = [this.timeDeltSecond(res.startTime), this.timeDeltSecond(res.endTime)] // 活动起止时间
        this.basicInfo.showTime = [this.timeDeltSecond(res.showStartTime), this.timeDeltSecond(res.showEndTime)] // 展示起止时间
        this.basicInfo.latType = res.latType.toString() // 满返纬度
        this.basicInfo.fullRule = res.fullRule.toString() // 满返规则
        this.basicInfo.fullRuleRule = res.fullRuleRule !== null ? res.fullRuleRule.toString() : '' // 满返规则
        this.basicInfo.joinType = res.joinType !== null ? res.joinType.toString() : '' // 参与此事
        this.basicInfo.fullReturnMoney = res.fullReturnMoney !== null ? res.fullReturnMoney.toString() : '' // 满返 金额 数量
        this.basicInfo.returnTimes = res.returnTimes !== null ? res.returnTimes.toString() : '' // 反多少次
        if (res.fileName === null) {
          this.fileName = [{name: ''}]
          this.primaryDisabled = false
        } else {
          this.fileName = [{name: res.fileName}]
          this.primaryDisabled = true
        }
        if (res.products !== '') {
          console.log('myjhdsh')
          this.goodsDetails = res.products
        }
        // this.primaryDisabled = res.fileName !== '' ? true : false
        this.redeemCodeDetails = res.tickets
        this.sendDetail = res.dtSendStatistics
        console.log(this.redeemCodeDetails)
        // if (this.basicInfo.doAction === '1') {
        for (var index = 0; index < res.tickets.length; index++) {
          var element = res.tickets[index]
          this.redeemCodeDetails[index].expiryDateType = element.expiryDateType.toString()
          this.redeemCodeDetails[index].ticketType = element.ticketType.toString()
          if (element.expiryDateType === '1') {
            // this.redeemCodeDetails.validity = res.redeemCodeDetails
            this.redeemCodeDetails[index].startTime = this.timeDeltSecond(element.startTime)
            this.redeemCodeDetails[index].endTime = this.timeDeltSecond(element.endTime)
            // console.log(element.expiryDateType)
          }
          if (element.expiryDateType === '2') {
            this.redeemCodeDetails[index].endTime = this.timeDeltSecond(element.endTime)
          }
          if (element.expiryDateType === '3') {
            this.redeemCodeDetails[index].days = element.days
          }
        }
        // }
        // console.log(this.redeemCodeDetails)
      },
      creatData (buttonType) { // 创建 提交 _data
        // 如果是 订单-阶梯 下边条件都置空
        this.basicInfo.providerRatio = this.selectSalesCosts.type === 2 ? this.basicInfo.providerRatio : 0
        this.basicInfo.fullRuleRule = this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1' ? '' : this.basicInfo.fullRuleRule  // 满返规则二
        this.basicInfo.fullReturnMoney = this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1' ? '' : this.basicInfo.fullReturnMoney // 满返金额数量
        this.basicInfo.returnTimes = this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1' ? '' : this.basicInfo.returnTimes // 返多少次
        this.basicInfo.joinType = this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1' ? '' : this.basicInfo.joinType // 参与次数 类型
        var dataInfo = {
          branchId: this.basicInfo.branchId, // 旧分公司id
          departmentId: this.basicInfo.departmentId, // 部门id
          newBranchId: this.newBranchId, // 新公司id
          createBranchId: this.branchOrgId, // 创建人新公司ID
          editBy: this.userName, // 编辑人 当前用户
          createBy: this.userName, // 创建人 当前用户
          userId: this.userId,
          batchId: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '', // 批次id
          id: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '', // 批次id
          buttonType: buttonType, // 创建或者保存
          gwId: this.roleId, // 岗位ID
          uorId: this.uorId // 用户id
        }
        // console.log(this.redeemCodeDetails)
        var _data = {}
        _data = Object.assign(this.basicInfo, this.basicInfo, dataInfo)
        // delete _data.showTime
        // delete _data.startStopTime
        // if (this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1') {
        var tickets = []
        for (var index = 0; index < this.redeemCodeDetails.length; index++) {
          var element = this.redeemCodeDetails[index]
          var redeemCodeDetailObj = {}
          redeemCodeDetailObj.fullMoney = this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1' ? element.fullMoney : '' // 满足金额
          redeemCodeDetailObj.ticketId = element.ticketId // 券id
          redeemCodeDetailObj.expiryDateType = Number(element.expiryDateType) // 有效期类型
          redeemCodeDetailObj.ticketType = element.ticketType // 优惠券类型
          redeemCodeDetailObj.ticketUser = element.ticketUser // 建券人
          redeemCodeDetailObj.ticketTimes = element.ticketTimes // 每人/数量
          redeemCodeDetailObj.phpTicketId = element.phpTicketId //
          if (Number(element.expiryDateType) === 1) {
            redeemCodeDetailObj.startTime = element.startTime
            redeemCodeDetailObj.endTime = element.endTime
            redeemCodeDetailObj.days = ''
          }
          if (Number(element.expiryDateType) === 2) {
            redeemCodeDetailObj.endTime = element.endTime
            redeemCodeDetailObj.days = ''
            redeemCodeDetailObj.startTime = ''
          }
          if (Number(element.expiryDateType) === 3) {
            redeemCodeDetailObj.endTime = ''
            redeemCodeDetailObj.startTime = ''
            redeemCodeDetailObj.days = element.days
          }
          tickets.push(redeemCodeDetailObj)
        }
        if (this.basicInfo.latType === '2' && this.basicInfo.fullRule === '2') {
          var products = []
          for (var i = 0; i < this.goodsDetails.length; i++) {
            products.push({'productId': this.goodsDetails[i].productId})
          }
          _data.products = products
        } else {
          _data.products = []
        }
        // goodsDetails
        _data.tickets = tickets
        // }
        return _data
      },
      onSubmitValid (buttonType, formName) { // 提交
        this.$refs[formName].validate((valid) => {
          this.formValidation()
          // var self = this
          if (valid) {
            if (this.basicInfo.latType === '2') {
              if (this.couponValid === true && this.goodsValid === true) {
                this.submit(buttonType)
              }
            } else {
              if (this.couponValid === true) {
                this.submit(buttonType)
              }
            }
          } else {
            this.message('请返回上一页填写必填项', 'error')
          }
        })
      },
      submit (buttonType) {
        var _data = this.creatData(buttonType)
        console.log(_data)
        // this.subDisabled = true
        activity.yhqhd.mfgl[this.isCreateOrUpdate](_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.message(this.text + '成功', 'success')
            this.cancel(this.menuId)
            // this.subDisabled = false
            this.$store.dispatch('mfState', this.$store.state.updateState.mfState + 1)
          } else {
            this.message(res.message, 'error')
            // this.subDisabled = false
          }
        })
      },
      formValidation () { // 提交表单验证
        // console.log(this.redeemCodeDetails)
        if (this.redeemCodeDetails.length !== 0) {
          for (var index = 0; index < this.redeemCodeDetails.length; index++) {
            var element = this.redeemCodeDetails[index]
            if (this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1') {
              if (Number(element.expiryDateType) === 1) {
                if ((element.startTime !== '' && element.endTime !== '') && element.fullMoney !== '' && element.ticketTimes !== '') {
                  if (moment(element.startTime).valueOf() >= moment(this.basicInfo.startTime).valueOf()) {
                    this.couponValid = true
                  } else {
                    this.message('活动开始时间小于等于优惠券开始时间', 'error')
                    this.basicInfo.startStopTime = []
                    this.couponValid = false
                  }
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
              if (Number(element.expiryDateType) === 2) {
                if (element.endTime !== '' && element.fullMoney !== '' && element.ticketTimes !== '') {
                  if (moment(element.endTime).valueOf() > moment(this.basicInfo.startTime).valueOf()) {
                    this.couponValid = true
                  } else {
                    this.message('活动开始时间小于优惠券结束时间', 'error')
                    this.basicInfo.startStopTime = []
                    this.couponValid = false
                  }
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
              if (Number(element.expiryDateType) === 3) {
                if (element.days !== '' && element.fullMoney !== '' && element.ticketTimes !== '') {
                  this.couponValid = true
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
            } else {
              if (Number(element.expiryDateType) === 1) {
                if ((element.startTime !== '' && element.endTime !== '') && element.ticketTimes !== '') {
                  if (moment(element.startTime).valueOf() >= moment(this.basicInfo.startTime)) {
                    this.couponValid = true
                  } else {
                    this.message('活动开始时间小于等于优惠券开始时间', 'error')
                    this.basicInfo.startStopTime = []
                    this.couponValid = false
                  }
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
              if (Number(element.expiryDateType) === 2) {
                if (element.endTime !== '' && element.ticketTimes !== '') {
                  if (moment(element.endTime).valueOf() > moment(this.basicInfo.startTime).valueOf()) {
                    this.couponValid = true
                  } else {
                    this.message('活动开始时间小于优惠券结束时间', 'error')
                    this.basicInfo.startStopTime = []
                    this.couponValid = false
                  }
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
              if (Number(element.expiryDateType) === 3) {
                if (element.days !== '' && element.ticketTimes !== '') {
                  this.couponValid = true
                } else {
                  this.message('第' + (index + 1) + '行有效期或每人/数量不为空/格式错误', 'error')
                  this.couponValid = false
                  break
                }
              }
            }
          }
        } else {
          this.couponValid = false
          this.message('优惠券不为空', 'error')
        }
        if (this.basicInfo.latType === '2') {
          if (this.goodsDetails.length !== 0) {
            this.goodsValid = true
          } else {
            this.goodsValid = false
            this.message('商品不为空', 'error')
          }
        }
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      nextStep (formName) { // 下一步
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.firstStep = false
            this.secondStep = true
            // this.redeemCodeDetails = []
            // console.log(this.basicInfo.latType)
            // console.log(this.basicInfo.fullReturnRules1)
            if (this.basicInfo.latType === '1' && this.basicInfo.fullRule === '1') { // 订单-阶梯
              this.isCoupon = true
              this.isGoods = false
            } else if (this.basicInfo.latType === '1' && this.basicInfo.fullRule === '2') { // 订单-每满
              this.isCoupon = true
              this.isGoods = false
            } else if (this.basicInfo.latType === '2' && this.basicInfo.fullRule === '2') { // 商品-每满
              this.isCoupon = true
              this.isGoods = true
            }
          }
        })
      },
      goBack () { // 返回上一步
        this.firstStep = true
        this.secondStep = false
        this.isCoupon = false
        // this.redeemCodeDetails = []
        this.choseCodeDisabled = false
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      daterangeFormat (t, text) { // 时间段格式化
        if (t) {
          // console.log(tGroup)
          if (text === '活动') {
            this.basicInfo.startTime = t[0]
            this.basicInfo.endTime = t[1]
            this.showTimeDisable = false
          } else {
            this.basicInfo.showStartTime = t[0]
            this.basicInfo.showEndTime = t[1]
          }
          // console.log(this.basicInfo)
        } else {
          if (text === '活动') {
            this.basicInfo.startStopTime = []
            this.basicInfo.startTime = ''
            this.basicInfo.endTime = ''
            this.showTimeDisable = true
          } else {
            this.basicInfo.showTime = []
            this.basicInfo.showStartTime = ''
            this.basicInfo.showEndTime = ''
          }
        }
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      },
      getDateStr (dayCount, time) {
        if (dayCount === null) {
          dayCount = 0
        }
        var dd = new Date(time)
        dd.setDate(dd.getDate() + dayCount) // 设置日期
        var y = dd.getFullYear()
        var m = dd.getMonth() + 1 // 获取当前月份的日期
        var d = dd.getDate()
        return y + '-' + m + '-' + d
      }
    },
    created () {
      this.url = 'http://' + apiHost.newCms + ':20000' + apiURL.fullReturn_upload
      console.log(this.url)
      this.menuId = this.$store.state.tab.menuId
      // console.log(this.$store.state.tab)
      if (this.$store.state.tab.uid) {
        this.isCreateOrUpdate = 'update'
        this.text = '编辑'
        // this.pageLoading = true
        this.$store.dispatch('pageLoading', true)
        this.searchDetail(this.$store.state.tab.uid)
        // this.searchSalesCosts(this.$store.state.tab.uid) // 查询促销费用
        if (this.branchId === 1) {
          this.brachDisabled = false
        } else {
          this.brachDisabled = true
        }
        this.searchCustomerType() // 查询客资类型
      } else {
        this.isCreateOrUpdate = 'create'
        this.text = '新增'
        if (this.branchId === 1) {
          this.brachDisabled = false
          this.basicInfo.branchId = this.branchId
          this.uploadData.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
        } else {
          this.brachDisabled = true
          this.showBranch = this.branchName
          this.showDept = this.deptName
          this.basicInfo.branchId = this.branchId
          this.uploadData.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
        }
        this.searchCustomerType() // 查询客资类型
        this.searchSalesCosts() // 查询促销费用
        // this.showBranchName = this.branchName // 新增是公司是当前用户的公司名称
        // this.showDeptName = this.deptName // 新增是公司是当前用户的公司名称
      }
      console.log(this.isCreateOrUpdate)
      console.log(this.branchId)
    },
    computed: mapState({
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      userId: function (state) {
        return state.user.info.user_id
      },
      roleId: function (state) {
        return state.user.info.roleid
      },
      uorId: function (state) {
        return state.user.info.uor_id
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      branchOrgId: function (state) {
        return state.user.info.branchOrgId
      },
      deptName: function (state) {
        return state.user.info.parOrgName
      },
      deptId: function (state) {
        return state.user.info.or_org_id
      }
    }),
    watch: {
      branchList (a, b) {
        this.getDeptList(this.basicInfo.branchId)
      }
    }
  }
</script>

<style>
.goodsDialog{width: 80%}
</style>





